<template>
  <div class="chat-form-container">
        <!-- 左侧预览区域 -->
    <div class="preview-section">
      <div class="preview-header">
        <h3>AI 问卷预览</h3>
        <el-button
          :disabled="!fields.length"
          class="save-btn"
          type="primary"
          @click="saveForm"
        >
          <el-icon>
            <ele-Download />
          </el-icon>
          保存问卷
        </el-button>
      </div>
      <div
        id="survey-content"
        class="survey-content"
      >
        <template v-if="fields.length">
          <FormPreview
            :fields="fields"
            :form-info="formInfo"
          />
        </template>
        <div
          v-else
          class="empty-state"
        >
          <el-empty description="暂无问卷内容">
            <template #description>
              <p>请在左侧输入提示词并点击生成按钮</p>
            </template>

          </el-empty>
        </div>
      </div>
    </div>
    <!-- 右侧输入区域 -->
    <div class="left-section">
      <!-- 生成卡片 -->
      <div class="generate-card">
        <div class="prompt-input">
          <h3>输入提示词</h3>
          <el-input
            v-model="promptText"
            :rows="10"
            placeholder="请输入您想要生成的问卷描述..."
            show-word-limit
            type="textarea"
          />
        </div>

        <div class="model-select">
          <span class="word-count mt10 mb10">您已输入提示词 {{ promptText.length }} 字</span>
          <el-select
            v-model="selectedModel"
            placeholder="选择模型"
          >
            <el-option
              label="deepseek-chat"
              value="deepseek-chat"
            />
            <!-- <el-option
              label="deepseek-reasoner"
              value="deepseek-reasoner"
            /> -->
          </el-select>
        </div>

        <el-button
          :disabled="isConnected || !promptText.trim()"
          :loading="isConnected"
          class="generate-btn"
          type="primary"
          @click="generateSurvey"
        >
          {{ isConnected ? "请等待，正在生成中..." : "开始生成问卷" }}
        </el-button>
      </div>

      <!-- 使用指南卡片 -->
      <div class="guide-card">
        <h4>
          <el-icon>
            <ele-Opportunity />
          </el-icon>
          使用指南
        </h4>
        <ol>
          <li>详细描述您需要的问卷主题和目的</li>
          <li>说明目标受众群体</li>
          <li>指定问卷预期长度和问题类型</li>
          <li>可以参考以下示例:</li>
        </ol>
        <div class="examples">
          <div
            v-for="(example, index) in examples"
            :key="index"
            class="example-item"
            @click="fillPrompt(example.content)"
          >
            <div class="example-content">
              {{ example.content }}
            </div>
          </div>
        </div>
      </div>
    </div>


  </div>
</template>

<script lang="ts" setup>
import { ref } from "vue";
import { useChatForm } from "./useChatForm";
import { parseJsonToFields } from "./convertToFields";
import FormPreview from "./FormPreview.vue";
import { watchThrottled } from "@vueuse/core";
import { jsonrepair } from "jsonrepair";
import { ElLoading, ElMessage, ElMessageBox } from "element-plus";
import { createFormRequest } from "@/api/project/form";
import { batchSaveProjectItem } from "@/views/formgen/api";
import { useRouter } from "vue-router";
import { formItemConvertData } from "@/views/formgen/utils/convert";

const promptText = ref("");
const selectedModel = ref("deepseek-chat");

const { openSendUserMsg, finalAnswer, isConnected } = useChatForm();

const generateSurvey = async () => {
  if (!promptText.value.trim()) return;

  if (fields.value.length > 0) {
    const result = await ElMessageBox.confirm("已存在生成的表单，是否继续生成并覆盖现有内容？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    }).catch(() => false);

    if (!result) return;
  }

  openSendUserMsg(promptText.value, selectedModel.value);
};

const fields = ref([]);
const formInfo = ref<{ title: string; description: string }>({ title: "", description: "" });
watchThrottled(
  () => finalAnswer.value,
  newVal => {
    try {
      console.log(newVal);
      const container = document.getElementById("survey-content");
      container!.scrollTo({
        top: container!.scrollHeight,
        behavior: "smooth" // 平滑滚动
      });
      console.log(newVal);

      const { fields: parseFields, formInfo: parseFormInfo } = parseJsonToFields(jsonrepair(newVal));
      fields.value = parseFields;
      formInfo.value = parseFormInfo;
    } catch (error) {
      console.error("解析JSON失败:", error);
    }
  },
  { throttle: 500 }
);

const examples = ref([
  {
    content: "写一份关于远程办公体验的调查问卷，共 5 个问题，关注工作效率、沟通方式、居家环境等。"
  },
  {
    content:
      "请生成一份针对大学生日常学习习惯的调查问卷，包含 10 个问题，涵盖学习时间安排、学习方法使用、学习环境选择等方面，问题类型包括单选和多选。"
  },
  {
    content: "需要一份关于职场人士工作压力的调查问卷，包含 15 个问题，主要调查工作强度、加班频率、压力来源、压力应对方式等内容。"
  },
  {
    content: "创建一份关于消费者网购行为的调查问卷，包含 12 个问题，调查网购频率、选择平台考虑因素、支付方式偏好等方面。"
  },
  {
    content: "创建一份关于消费者对健康食品认知的调查问卷，共 10 个问题，关注购买习惯、标签认知、品牌信任等。"
  }
]);

const fillPrompt = (content: string) => {
  promptText.value = content;
};

const scrollToPrompt = () => {
  const promptInput = document.querySelector(".prompt-input textarea") as HTMLTextAreaElement;
  if (promptInput) {
    promptInput.focus();
  }
};

const router = useRouter();

const saveForm = async () => {
  const loading = ElLoading.service({
    lock: true,
    text: "保存中...",
    background: "rgba(255, 255, 255, 0.7)"
  });

  try {
    const res = await createFormRequest({
      name: formInfo.value?.title,
      type: 1,
      description: formInfo.value?.description,
      fields: fields.value
    });

    await batchSaveProjectItem({
      formKey: res.data.formKey,
      list: fields.value.map(item => formItemConvertData(item, res.data.formKey)),
      operation: "add"
    });

    loading.close();

    await ElMessageBox.confirm("已经保存为新的表单，是否前去编辑？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    }).then(() => {
      router.push({
        path: `/project/form/editor/index`,
        query: { key: res.data.formKey, active: "editor/index", type: 1 }
      });
    });
  } catch (error) {
    loading.close();
    ElMessage.error("保存失败");
  }
};
</script>

<style lang="scss" scoped>
.chat-form-container {
  display: flex;
  gap: 20px;
  height: calc(100vh - 40px); // 设置容器高度，减去padding

  .left-section {
    flex: 0.8;
    display: flex;
    flex-direction: column;
    gap: 16px;
    height: 100%; // 确保左侧区域占满高度
  }

  .generate-card,
  .guide-card,
  .preview-section {
    background: #fff;
    border-radius: 8px;
    padding: 30px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  }

  .generate-card {
    flex: 0 0 auto; // 根据内容确定高度
    .prompt-input {
      h3 {
        font-size: 16px;
        font-weight: normal;
        color: #333;
        margin-bottom: 10px;
      }

      :deep(.el-textarea__inner) {
        min-height: 160px !important;
        border-radius: 8px;
        background: #f9f9f9;
        border: none;
        padding: 16px;

        &::placeholder {
          color: #999;
        }
      }
    }

    .model-select {
      margin: 6px 0 16px;
      display: flex;
      justify-content: space-between;
      align-items: flex-start;
      flex-direction: column;

      .word-count {
        color: #999;
        font-size: 14px;
        margin-bottom: 5px;
      }

      :deep(.el-select) {
        .el-input {
          .el-input__wrapper {
            background: #f9f9f9;
            border: none;
            box-shadow: none;
          }
        }
      }
    }

    .generate-btn {
      width: 100%;
      height: 44px;
      font-size: 15px;
      border: none;
      background: linear-gradient(to right, #7742d9, #a676ff);
      transition: opacity 0.3s;

      &:hover {
        background: linear-gradient(to right, #7742d9, #a676ff);
        opacity: 0.9;
      }

      &:active {
        opacity: 0.8;
      }
    }
  }

  .guide-card {
    flex: 1; // 占用剩余空间
    overflow-y: auto; // 内容过多时可滚动
    h4 {
      color: #333;
      font-size: 15px;
      font-weight: normal;
      display: flex;
      align-items: center;
      gap: 8px;
      line-height: 25px;
      margin-bottom: 16px;

      .el-icon {
        color: #8957e5;
      }
    }

    ol {
      color: #666;
      font-size: 14px;
      line-height: 1.8;
      padding-left: 20px;
      margin-bottom: 16px;

      li {
        margin-bottom: 8px;
      }
    }

    .examples {
      .example-item {
        background: #f8f9fa;
        border-radius: 8px;
        padding: 9px;
        color: #666;
        font-size: 14px;
        line-height: 1.6;

        &:hover {
          background: #f0f0f0;
          cursor: pointer;
        }

        &:not(:last-child) {
          border-bottom: 1px solid rgba(0, 0, 0, 0.06);
          margin-bottom: 12px;
        }

        .example-content {
          color: #666;
          font-size: 14px;
          line-height: 1.6;
          padding: 8px 0;
        }
      }
    }
  }

  .preview-section {
    flex: 1;
    display: flex;
    flex-direction: column;
    height: 100%; // 确保右侧预览区域占满高度

    .preview-header {
      flex: 0 0 auto;
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;

      .save-btn {
        height: 32px;
        padding: 0 16px;
        border-radius: 6px;
        background: #f0e6ff;
        border: none;
        color: #7742d9;
        font-size: 14px;
        margin-right: 15px;

        &:hover {
          background: #e8daff;
        }

        &:active {
          background: #e0d0ff;
        }

        &.is-disabled {
          background: #f5f7fa;
          color: #c0c4cc;
        }

        .el-icon {
          margin-right: 4px;
        }
      }
    }

    .survey-content {
      flex: 1;
      overflow-y: auto; // 内容过多时可滚动
      min-height: 0; // 确保滚动正常工作
      border: 1px solid #eee;
      border-radius: 4px;
      padding: 20px;

      .empty-state {
        height: 100%;
        display: flex;
        align-items: center;
        justify-content: center;

        :deep(.el-empty__description) {
          p {
            color: #909399;
            margin: 10px 0;
          }
        }

        .generate-prompt-btn {
          height: 32px;
          padding: 0 16px;
          border-radius: 6px;
          background: #f0e6ff;
          border: none;
          color: #7742d9;
          font-size: 14px;

          &:hover {
            background: #e8daff;
          }

          &:active {
            background: #e0d0ff;
          }

          .el-icon {
            margin-left: 4px;
          }
        }
      }
    }
  }
}
</style>
